package token

import (
	"context"
	"errors"
	"protobuf-learn/proto"

	"google.golang.org/grpc/credentials"
)

type TokenIssuer interface {
	IssueToken(ctx context.Context, userId string) (string, error)
}

type jwtCredentials struct {
	tokenIssuer TokenIssuer
}

func NewJwtCredentials(tokenIssuer TokenIssuer) (*jwtCredentials, error) {
	if tokenIssuer == nil {
		return nil, errors.New("token issuer must not be nil")
	}
	return &jwtCredentials{
		tokenIssuer: tokenIssuer,
	}, nil
}

func (j *jwtCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	reqInfo, ok := credentials.RequestInfoFromContext(ctx)
	if !ok || reqInfo.Method != proto.InterceptorService_Protected_FullMethodName {
		return nil, nil
	}

	token, err := j.tokenIssuer.IssueToken(ctx, "user-id-123456")
	if err != nil {
		return nil, err
	}

	return map[string]string{
		"authorization": token,
	}, nil
}

func (j *jwtCredentials) RequireTransportSecurity() bool {
	return false
}
